/*

Last commit by $Author: obooklage@gmail.com $
Date - $Date: 2011-04-04 10:43:14 +0000 (Mon, 04 Apr 2011) $
Revision - $Rev: 32 $
Id : $Id: mainwindow.cpp 32 2011-04-04 10:43:14Z obooklage@gmail.com $

*/


/* Embeded VLC :

    add a QFrame

Linux :
-----
Add in *.pro file :

LIBS += -L/usr/lib -lvlc

Windows :
-------
Add in *.pro file :

LIBS += -L"C:/Program Files/VideoLAN/VLC"
LIBS += -lvlc

*/

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QtDebug>
#include <QStatusBar>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    // Init

    this->setWindowTitle("FreeEasyTV");

    // Setting the main window icon
    QFile icon( QCoreApplication::applicationDirPath() + "/tv.png");
    if( icon.exists() == true )
    {
        this->setWindowIcon(QIcon(icon.fileName()));
    }

    // Nouveau :

    _vlcinstance = NULL;
    player = NULL;
    media = NULL;

#ifdef Q_OS_WIN32
    const char *optionDeVlc[] = {
        "--plugin-path","C:\\Program Files\\VideoLAN\\VLC"
     };
#else
    const char *optionDeVlc[] = {""};
#endif

    _vlcinstance = libvlc_new(sizeof(optionDeVlc) / sizeof(optionDeVlc[0]),optionDeVlc);
    if( _vlcinstance == NULL )
    {
        QMessageBox::information( this, "libvlc_new", "Problem : libvlc_new is NULL" );
        return;
    }
    
    player = libvlc_media_player_new(_vlcinstance);
    if( player == NULL )
    {
        QMessageBox::information( this, "libvlc_media_player_new", "Problem : libvlc_media_player_new is NULL" );
        return;
    }
    
   // libvlc_video_set_mouse_input(player,true);
    libvlc_video_set_mouse_input(player,false);

#if defined(Q_OS_MAC)
    libvlc_media_player_set_nsobject(player ,ui->frame->winId());
#elif defined(Q_OS_UNIX)
    libvlc_media_player_set_xwindow(player ,ui->frame->winId());
#elif defined(Q_OS_WIN)
    libvlc_media_player_set_hwnd(player,ui->frame->winId());
#endif

    libvlc_audio_set_volume (player, 20);

    media = libvlc_media_new_location(_vlcinstance, "rtsp://mafreebox.freebox.fr/fbxtv_pub/stream?namespace=1&service=201&flavour=ld");
    if( media == NULL )
    {
        QMessageBox::information( this, "libvlc_media_new_location", "Problem : libvlc_media_new_location is NULL" );
        return;
    }   
    
    libvlc_media_player_set_media(player,media);
    libvlc_media_add_option(media,":video-filter=deinterlace");
    libvlc_media_add_option(media,":deinterlace-mode=blend");
    desinterlace_on = true;
    ui->checkBox_Desinterlace->setChecked(true);

    libvlc_video_set_mouse_input(player,false);

    libvlc_media_player_play(player);

    ui->horizontalSlider->setSliderPosition(20);

    // Request playlist

    manager = new QNetworkAccessManager(this);
    connect(manager, SIGNAL(finished(QNetworkReply*)),this, SLOT(replyFinished(QNetworkReply*)));
    manager->get(QNetworkRequest(QUrl("http://mafreebox.freebox.fr/freeboxtv/playlist.m3u")));

    ui->centralWidget->setMouseTracking(false); // ne change pas grand chose ;(

    TimerCount = 0;
    HidedRemote = false;
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(TimerTimeout()));
    timer->start(1000);

    ui->groupBoxRemote->hide();

    statusBar()->showMessage("Ready");

}

MainWindow::~MainWindow()
{
    PlayerStop();

    if( player != NULL )
   	 libvlc_media_player_release(player);
   	 
    if( _vlcinstance != NULL )  	 
    	libvlc_release(_vlcinstance); // last operation

    delete ui;
}

// Auto-Hide remote
void MainWindow::TimerTimeout()
{

    TimerCount++;

    if( ( TimerCount >  10 ) && ( HidedRemote == false ) )
    {
        ui->groupBoxRemote->hide();
        HidedRemote = true;
        TimerCount=0;
    }
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::mouseMoveEvent( QMouseEvent * ev )
{
    if( TimerCount > 3)
    {
        ui->groupBoxRemote->show();
        HidedRemote = false;
    }

    TimerCount = 0;
}

// Playlist

void MainWindow::replyFinished(QNetworkReply* Reply)
{
static QUrl old_redirection= QUrl("");

    // handle http redirection :

    QVariant possibleRedirectUrl = Reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
    if( ( !possibleRedirectUrl.isNull() ) && ( possibleRedirectUrl.toUrl() != old_redirection ) ) // no loop !
    {
        qDebug() <<  "redirection to " << possibleRedirectUrl;
        old_redirection = possibleRedirectUrl.toUrl();
        manager->get(QNetworkRequest(possibleRedirectUrl.toUrl()));
        return;
    }

    // Channels :

    QList<QByteArray> list = Reply->readAll().split('\n'); // c'est de l'UTF8 !!
    QString channel_name;
    foreach(QString line, list)
    {
        if( line.startsWith("#EXTINF"))
        {
            channel_name = line.section('-',1);
        }
        else if( (line.startsWith("rtsp://")) )
        {
            QByteArray true_name = channel_name.trimmed().toLatin1();
            QListWidgetItem *item = new QListWidgetItem(QString::fromUtf8(true_name.data(),true_name.size()));
            item->setData(Qt::UserRole,QVariant(line));
            ui->listWidget->addItem(item);
        }
    }

    Reply->deleteLater();
}


void MainWindow::on_horizontalSlider_sliderMoved(int position)
{
    PlayerChangeVolume(position);
}


void MainWindow::on_horizontalSlider_valueChanged(int value)
{
    PlayerChangeVolume(value);
}

// Channel double-clicked

void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem* item)
{
    qDebug() <<  "Channel change to : " << item->data(Qt::UserRole)  << "Name : " << item->text();
    PlayerStop();
    PlayerPlay( item->data(Qt::UserRole).toString() , item->text());
    TimerCount = 0;
}

void MainWindow::PlayerStop()
{
    libvlc_media_player_stop(player);
    while( libvlc_media_player_is_playing(player) != 0 )
    {
    }
}

void MainWindow::PlayerPlay(QString url,QString text)
{

    PlayerStop();

    libvlc_media_release(media);
    media = libvlc_media_new_location (_vlcinstance, url.toAscii());
    libvlc_media_player_set_media(player,media);
    this->setWindowTitle("FreeEasyTV - " + text);
    ui->checkBox_Desinterlace->setCheckState(Qt::Checked);
    libvlc_media_add_option(media,":video-filter=deinterlace");
    libvlc_media_add_option(media,":deinterlace-mode=blend");
    desinterlace_on = true;

    libvlc_media_player_play(player);
}

void MainWindow::PlayerChangeVolume( int volume )
{
    libvlc_audio_set_volume (player, volume );
}

void MainWindow::on_checkBox_Desinterlace_stateChanged(int )
{

    PlayerStop();

    if( ui->checkBox_Desinterlace->isChecked() == true )
    {
        qDebug() <<  "On désinterlace";
        libvlc_media_add_option(media,":video-filter=deinterlace");
        libvlc_media_add_option(media,":deinterlace-mode=blend");
    }
    else
    {
        qDebug() <<  "On ne désinterlace ** PAS **";
        libvlc_media_add_option(media,":video-filter=deinterlace");
        libvlc_media_add_option(media,":deinterlace-mode=disabled");
    }

    libvlc_media_player_set_media(player,media);
    libvlc_media_player_play(player);

}

void MainWindow::on_pushButton_Hide_clicked()
{
    ui->groupBoxRemote->hide();
    HidedRemote = true;
    TimerCount=2;
}

void MainWindow::on_checkBox_Mute_clicked()
{
static int volume;

    if( ui->checkBox_Mute->isChecked() == true)
    {
        volume = libvlc_audio_get_volume(player);
        libvlc_audio_set_volume(player,0);
    }
    else
    {
        libvlc_audio_set_volume(player,volume);
    }
}

void MainWindow::on_actionControles_triggered()
{
    ui->groupBoxRemote->show();
    HidedRemote = false;
    TimerCount = 0;
}


/*

 Unused for instance ..

 */

void MainWindow::on_checkBox_FullScreen_clicked()
{

    return;


static bool isFullscreen = false;

const Qt::WindowStates curstate = ui->frame->windowState();
Qt::WindowStates newstate = curstate;
Qt::WindowFlags  newflags = ui->frame->windowFlags();

if( (ui->checkBox_FullScreen->isChecked() == true) && (isFullscreen==false) )
    {
        qDebug() <<  "Fullscreen ** ON **";
        newstate |= Qt::WindowFullScreen;
        newflags |= Qt::WindowStaysOnTopHint;

        PlayerStop();
        ui->frame->setWindowState( newstate );
        ui->frame->setParent( NULL );
        ui->frame->setWindowFlags( newflags );
        ui->frame->show();
        libvlc_media_player_play(player);

        isFullscreen=true;
    }
    else if ( isFullscreen == true )
    {
        qDebug() <<  "Fullscreen ** OFF **";
        newstate &= ~Qt::WindowFullScreen;
        newflags &= ~Qt::WindowStaysOnTopHint;

         ui->frame->setWindowFlags( newflags );
         // layout->addWidget( reparentable );
        // ui->frame->setParent( this->ui );
         ui->frame->setWindowState( newstate );

/*
+        reparentable->setWindowFlags( newflags );
         layout->addWidget( reparentable );
         reparentable->setWindowState( newstate );

         */

        isFullscreen=false;
    }
}
